package top.choviwu.garbage.sort.util;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
public class IpUtils {

    public static final String TAOBAO_IP = "http://ip.taobao.com/service/getIpInfo.php?ip=";

    private static final int MAX_RETRY_TIMES = 5;

    private static final int MAX_REQUEST_TIMEOUT = 3*1000;

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        log.info("User IP is >_<   {}",ip);
        return ip;
    }

    public static Map<String,Object>    getAddress(String ip){
        int failCount = 0;
        Map map = null;
        try {
            HttpResponse response = HttpUtil.createGet(TAOBAO_IP+ip).timeout(MAX_REQUEST_TIMEOUT).execute();
            log.info(">>>>>>>>>Result:{} ",response.body());
            if(response.isOk()){
                Map object = JsonUtils.toObj(response.body(),Map.class);
                log.info("Map >>>>>>{}",response.body());
                return (Map<String, Object>) object.get("data");
            }
        }catch (Exception e){
            e.printStackTrace();
            return MapUtil.newHashMap();
        }
        return MapUtil.newHashMap();
    }

    public static void main(String[] args) {

        System.out.println(getAddress(" 113.88.138.6").get("city"));
    }

}
